
package com.bbh.plugin.single.privilege.demo.controller;


import com.bbh.plugin.single.privilege.core.entity.Account;
import com.bbh.plugin.single.privilege.core.entity.AccountApp;
import com.bbh.plugin.single.privilege.core.enums.BaseEnum;
import com.bbh.plugin.single.privilege.core.service.*;
import com.bbh.plugin.single.privilege.core.vo.RoleTableVo;
import com.bbh.plugin.single.privilege.core.vo.tree.RoleVo;
import com.bbh.common.base.vo.GridVo;
import com.bbh.common.domain.*;
import com.bbh.common.utils.IdUtils64;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/account")
public class AccountController extends BasicController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountRoleService accountRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AccountAppService accountAppService;
    @Autowired
    private AppService appService;
    @Value("${system.appKey}")
    private String systemAppKey;

    @RequestMapping(value = VIEW_FILED + "/index", method = RequestMethod.GET)
    public String index(ModelMap model) {

        return "single/account/index";
    }


    @RequestMapping(value = VIEW_FILED + "/list")
    public
    @ResponseBody
    GridVo list(HttpServletRequest request, String companyCode, String orgCode) throws ServletRequestBindingException {
        Condition condition = new Condition();
        condition.putEquals("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        GridVo vo = new GridVo();
        List<Order> orderList = new ArrayList<>();
        orderList.add(new Order("sort", "ASC"));
        Page<Account> pageResult = accountService.selectPage(condition, orderList, initPageRequest(request, PAGE_NUMBER, PAGE_ROWS));
        return new GridVo(pageResult);
    }


    /**
     * 跳转到edit页面
     *
     * @return
     */
    @RequestMapping(UPDATE_FILED + "/edit")
    public String toEdit(String id, Model model, String type) {

        if ("edit".equals(type)) {
            Assert.notNull(id, "参数错误");
            Account account;
            account = accountService.selectByPrimaryKey(id);
            model.addAttribute("account", account);
            Condition condition = new Condition();
            condition.putEquals("accountId", id);

            String appKey = "";
            List<AccountApp> appKeys = accountAppService.selectList(condition, null);
            if (appKeys.size() > 0) {
                for (AccountApp code : appKeys) {
                    appKey += code.getAppCode() + ",";
                }
                appKey = appKey.substring(0, appKey.length() - 1);
                model.addAttribute("appKey", appKey);
            }
            model.addAttribute(OPERATE_TYPE, "edit");
        }
        if ("add".equals(type)) {
            model.addAttribute(OPERATE_TYPE, "add");
        }
        return "single/account/edit";
    }


    @RequestMapping(value = INSERT_FILED + "/insert")
    public
    @ResponseBody
    Message insert(@Validated Account account, String appKey) {
        if(StringUtils.isBlank(appKey)){
            appKey=systemAppKey;
        }
        Condition condition = new Condition();
        if (StringUtils.isNotBlank(account.getLoginName())) {
            condition.putEquals("loginName", account.getLoginName());
        }
        if (!accountService.existsCheckEach(condition)) {
            Date date = new Date();
            account.setPassword(DigestUtils.md5DigestAsHex(account.getPassword().getBytes()));
            account.setCreateTime(date);
            account.setModifyTime(date);
            account.setCreateBy(getLoginName());
            account.setModifyBy(getLoginName());
            account.setDataStatus(BaseEnum.DATA_STATUS.NORMAL.getKey());
            account.setId(IdUtils64.getInstance().getStringId());
            accountService.insertAccountAndAppCode(account, appKey);
            return new Message(StatusType.SUCCESS.getKey(), "增加成功");
        }
        return new Message(StatusType.WARN.getKey(), "登录名已存在，不能重复增加");
    }

    /**
     * update
     *
     * @return
     */
    @RequestMapping(UPDATE_FILED + "/update")
    public
    @ResponseBody
    Message update(@Validated Account account, String appKey) {
        if(StringUtils.isBlank(appKey)){
            appKey=systemAppKey;
        }
        Assert.notNull(account.getId(), "参数错误");
        Account modifyAccount = accountService.selectByPrimaryKey(account.getId());
        if (modifyAccount != null) {
            Condition conditionNew = new Condition();
            if (StringUtils.isNotBlank(account.getLoginName())) {
                conditionNew.putEquals("loginName", account.getLoginName());
            }
            Condition entityCondition = new Condition();
            entityCondition.putEquals("loginName", modifyAccount.getLoginName());
            if (!accountService.existsUpdateCheckEach(conditionNew, entityCondition)) {
                Date date = new Date();
                modifyAccount.setPhoto(account.getPhoto());
                modifyAccount.setName(account.getName());
                modifyAccount.setLoginName(account.getLoginName());
                modifyAccount.setIsEnabled(account.getIsEnabled());
                modifyAccount.setModifyBy(getLoginName());
                modifyAccount.setModifyTime(date);
                modifyAccount.setDescription(account.getDescription());
                modifyAccount.setEmail(account.getEmail());
                modifyAccount.setPhone(account.getPhone());
                modifyAccount.setMobile(account.getMobile());
                modifyAccount.setSort(account.getSort());
                accountService.updateAccountAndAppCode(modifyAccount, appKey);
                return new Message(StatusType.SUCCESS.getKey(), "更新成功");
            }
            return new Message(StatusType.WARN.getKey(), "登录名已存在，不能重复增加");
        }
        return new Message(StatusType.WARN.getKey(), "参数错误");
    }

    @RequestMapping(DELETE_FILED + "/delete")
    public
    @ResponseBody
    Message delete(@RequestParam(value = "ids[]") String[] ids) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                Account account = accountService.selectByPrimaryKey(id);
                if (account != null) {
                    account.setDataStatus(BaseEnum.DATA_STATUS.DELETE.getKey());//设置为不可用
                    account.setModifyBy(getLoginName());
                    account.setModifyTime(new Date());
                    accountService.updateByPrimaryKeySelective(account);
                }
            }
        }

        Message message = new Message(StatusType.SUCCESS.getKey(), "删除成功");
        return message;
    }

    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping(VIEW_FILED + "/authorization/edit")
    public String authorizationEdit(HttpServletRequest request, Model model) throws ServletRequestBindingException {
        model.addAttribute("id", request.getParameter("id"));
        return "single/account/authorization";
    }


    /**
     * 授权
     *
     * @return
     */
    @RequestMapping(INSERT_FILED + "/authorization/insert")
    public
    @ResponseBody
    Message authorizationInsert(@RequestParam(value = "ids[]") String[] ids, @RequestParam(value = "roleIds[]") String[] roleIds, String accountId, HttpServletRequest request) throws ServletRequestBindingException {
        Assert.notNull(accountId, "参数错误");
        int count = accountRoleService.updateRole(ids, roleIds, accountId);
        if (count == 0) {
            return new Message(StatusType.ERROR.getKey(), "参数错误");
        }
        return new Message(StatusType.SUCCESS.getKey(), "保存成功");
    }


    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping(VIEW_FILED + "/authorization/list")
    public
    @ResponseBody
    RoleTableVo authorizationList(String accountId, String roleName, String roleEName, HttpServletRequest request, Model model) throws ServletRequestBindingException {
        Assert.notNull(accountId, "参数错误");//userId 不能为空
        Condition params = new Condition();
        params.put("accountId", accountId);
        params.put("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        if (StringUtils.isNoneBlank(roleName)) {
            params.put("roleName", roleName);
        }
        if (StringUtils.isNoneBlank(roleEName)) {
            params.put("enname", roleEName);
        }
        RoleTableVo vo = new RoleTableVo();
        Page<RoleVo> pageResult = roleService.findUserRolePage(params, initPageRequest(request, PAGE_NUMBER, PAGE_ROWS));
        String s = "";
        if (pageResult.getTotal() > 0) {
            for (RoleVo roleVo : pageResult.getList()) {
                if (roleVo.getIsCheck()) {
                    s += roleVo.getId() + ",";
                }
            }
            if (StringUtils.isNotEmpty(s)) {
                s = s.substring(0, s.length() - 1);
            }
            model.addAttribute("roleIds", s);
        }
        vo.setRows(pageResult.getList());
        vo.setTotal(pageResult.getPages());//总页数
        vo.setRecords(pageResult.getTotal());//总记录数
        vo.setRoleIds(s);
        return vo;
    }

    @RequestMapping(UPDATE_FILED + "/password/init")
    public
    @ResponseBody
    Message passwordInit(@Valid Account account) {
        Assert.notNull(account.getId(), "参数错误");
        Account editAccount = accountService.selectByPrimaryKey(account.getId());
        if (editAccount != null) {
            editAccount.setModifyTime(new Date());
            accountService.entryptPassword(editAccount);
            accountService.updateByPrimaryKeySelective(editAccount);
        }
        Message message = new Message(StatusType.SUCCESS.getKey(), "密码初始化成功");
        return message;
    }

    @RequestMapping(UPDATE_FILED + "/changeLocked")
    public
    @ResponseBody
    Message changeLocked(@RequestParam(value = "ids[]") String[] ids) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                Account editAccount = accountService.selectByPrimaryKey(id);
                if (editAccount != null) {
                    editAccount.setIsLocked(false);
                    editAccount.setModifyTime(new Date());
                    editAccount.setModifyBy(getLoginName());
                    accountService.updateByPrimaryKeySelective(editAccount);
                }
            }
        }
        Message message = new Message(StatusType.SUCCESS.getKey(), "解锁成功");
        return message;
    }



}